<!-- src/components/SliderCaptcha.vue -->
<template>
	<div
		class="relative w-full h-12 bg-gray-200 dark:bg-gray-700 rounded-md overflow-hidden select-none"
	>
		<div
			class="absolute top-0 left-0 h-full bg-emerald-500/50 dark:bg-emerald-400/50"
			:style="{ width: `${sliderValue}%` }"
		></div>
		<div
			class="absolute top-0 left-0 h-full w-12 bg-white dark:bg-gray-800 border-2 border-gray-300 dark:border-gray-500 rounded-md cursor-pointer flex items-center justify-center shadow-lg"
			:style="{ left: `calc(${sliderValue}% - ${sliderValue * 0.48}px)` }"
			@mousedown="startDrag"
		>
			<svg
				xmlns="http://www.w3.org/2000/svg"
				class="h-6 w-6 text-gray-500"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="2"
					d="M9 5l7 7-7 7"
				/>
			</svg>
		</div>
		<span
			class="absolute inset-0 flex items-center justify-center text-gray-500 dark:text-gray-400 transition-opacity duration-300"
			:class="{ 'opacity-0': sliderValue > 10 }"
		>
			请向右滑动进行验证
		</span>
		<span
			v-if="isVerified"
			class="absolute inset-0 flex items-center justify-center text-emerald-600 dark:text-emerald-400 font-semibold"
		>
			验证成功
		</span>
	</div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { CaptchaApi } from "@/apis/index"; // 假设你的API在 @/api/user

const emit = defineEmits(["success"]);

const sliderValue = ref(0);
const isDragging = ref(false);
const isVerified = ref(false);

const startDrag = (event: MouseEvent) => {
	console.log("startDrag" , event);
	
	if (isVerified.value) return;
	isDragging.value = true;
	document.addEventListener("mousemove", onDrag);
	document.addEventListener("mouseup", stopDrag);
};

const onDrag = (event: MouseEvent) => {
	if (!isDragging.value) return;
	const container = (event.currentTarget as HTMLElement)?.parentElement
		?.parentElement;
	if (!container) return;

	const rect = container.getBoundingClientRect();
	let newValue = ((event.clientX - rect.left) / rect.width) * 100;

	if (newValue < 0) newValue = 0;
	if (newValue > 100) newValue = 100;

	sliderValue.value = newValue;
};

const stopDrag = async () => {
	isDragging.value = false;
	document.removeEventListener("mousemove", onDrag);
	document.removeEventListener("mouseup", stopDrag);

	if (sliderValue.value >= 98) {
		// 容错范围
		try {
			// 假设 behavior=1 代表登录滑块验证
			const success = await CaptchaApi([1]);
			if (success) {
				isVerified.value = true;
				sliderValue.value = 100;
				emit("success");
			} else {
				reset();
			}
		} catch (error) {
			console.error("Captcha verification failed:", error);
			reset();
		}
	} else {
		reset();
	}
};

const reset = () => {
	sliderValue.value = 0;
	isVerified.value = false;
};

defineExpose({ reset });
</script>
